package cn.qicaiwang.open.app.server.Impl;

import cn.qicaiwang.open.app.entity.LegalDocument;
import cn.qicaiwang.open.app.mapper.LegalDocumentMapper;
import cn.qicaiwang.open.app.server.LegalDocumentService;
import cn.qicaiwang.open.common.utils.StringUtils;
import cn.qicaiwang.open.qiniu.utils.QiNiuUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class LegalDocumentServiceImpl implements LegalDocumentService {

    @Autowired
    private LegalDocumentMapper legalDocumentMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public LegalDocument uploadPdfDocument(MultipartFile file,
                                           String documentName,
                                           String categoryLevel1,
                                           String categoryLevel2) {
        // 1. 增强文件验证
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
    /*    if (!"application/pdf".equals(file.getContentType())) {
            throw new IllegalArgumentException("只支持PDF文件上传");
        }*/
        if (file.getSize() > 50 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过50MB");
        }
        if (StringUtils.isBlank(categoryLevel1)) {
            throw new IllegalArgumentException("一级分类不能为空");
        }

        // 2. 上传到七牛云
        String fileKey = QiNiuUtil.uploadMultipartFile(file, null);
        if (fileKey == null) {
            throw new RuntimeException("文件上传到七牛云失败");
        }

        // 3. 构造下载URL
        String downloadUrl = "http://qcwimg.it110.top/" + fileKey;

        // 4. 保存到数据库
        LegalDocument document = new LegalDocument();
        document.setDocumentName(documentName); // 使用从文件获取的名称
        document.setDocumentKey(fileKey);
        document.setDocumentUrl(downloadUrl);
        document.setDocumentSize(file.getSize());
        document.setCategoryLevel1(categoryLevel1);
        document.setCategoryLevel2(categoryLevel2);
        document.setStatus(1);

        try {
            legalDocumentMapper.insert(document);
        } catch (Exception e) {
            QiNiuUtil.delete(fileKey);
            throw new RuntimeException("文书信息保存失败", e);
        }

        return document;
    }

    @Override
    public LegalDocument getDocumentById(Long id) {
        return null;
    }

    @Override
    public List<LegalDocument> getDocumentsByCase(String caseNumber) {
        return null;
    }

    @Override
    public List<LegalDocument> getDocumentsByType(String documentType) {
        return null;
    }

    @Override
    public LegalDocument updateDocumentInfo(LegalDocument document) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDocument(Long id) {
        // 1. 查询文档信息
        LegalDocument document = legalDocumentMapper.selectById(id);
        if (document == null) {
           // log.warn("尝试删除不存在的文档，ID: {}", id);
            return false;
        }

        // 2. 先删除数据库记录
        int deleteCount = legalDocumentMapper.deleteById(id);
        if (deleteCount <= 0) {
           // log.error("数据库记录删除失败，ID: {}", id);
            return false;
        }

        // 3. 删除七牛云文件（即使失败也不回滚数据库删除）
        if (StringUtils.isNotBlank(document.getDocumentKey())) {
            try {
                boolean qiniuDeleted = QiNiuUtil.delete(document.getDocumentKey());
                if (!qiniuDeleted) {
                  //  log.error("七牛云文件删除失败，Key: {}", document.getDocumentKey());
                    // 这里可以选择记录失败但不抛出异常，因为数据库记录已删除
                }
            } catch (Exception e) {
               // log.error("删除七牛云文件时发生异常，Key: {}", document.getDocumentKey(), e);
            }
        }

        return true;
    }

    @Override
    public LegalDocument replaceDocumentFile(Long id, MultipartFile newFile) {
        return null;
    }

    @Override
    public List<LegalDocument> getAllValidDocuments() {
        return null;
    }





    @Override
    public List<String> getLevel2CategoriesByLevel1(String level1) {
        QueryWrapper<LegalDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT category_level2")
                .eq("category_level1", level1)
                .eq("status", 1)
                .isNotNull("category_level2")
                .ne("category_level2", "");
        return legalDocumentMapper.selectList(queryWrapper)
                .stream()
                .map(LegalDocument::getCategoryLevel2)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getLevel3CategoriesByLevel2(String level2) {
        QueryWrapper<LegalDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT category_level3")
                .eq("category_level2", level2);  // 只保留这个必要条件

        return legalDocumentMapper.selectList(queryWrapper)
                .stream()
                .map(LegalDocument::getCategoryLevel3)
                .filter(Objects::nonNull)   // 过滤掉null值
                .filter(s -> !s.isEmpty())  // 过滤掉空字符串
                .collect(Collectors.toList());
    }

    @Override
    public Page<LegalDocument> getDocumentsByLevel3(Page<LegalDocument> page, String level3) {
        QueryWrapper<LegalDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_level3", level3)
                .eq("status", 1)
                .orderByDesc("upload_time"); // 默认按上传时间倒序

        return legalDocumentMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<LegalDocument> getDynamics() {

            // 1. 使用Lambda+字段选择（避免N+1查询问题）
            LambdaQueryWrapper<LegalDocument> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .select(LegalDocument::getCategoryLevel3,
                            LegalDocument::getDocumentUrl) // 建议增加必要字段
                    .eq(LegalDocument::getCategoryLevel1, "普法动态"); // 确认数据库实际存储值

            return legalDocumentMapper.selectList(queryWrapper);

    }
}
